<template>
  <div class="h-100 flex-1 flex-column">
    <div class="flex flex-wrap justify-end">
      <el-select v-model="form.bizType" size="mini" style="width: 200px" class="mb-10" clearable :placeholder="$t('PROCESS_TYPE')">
        <el-option
          v-for="(item, index) in dictList.BUSINESS_TYPES"
          :key="index"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-select v-model="form.status" size="mini" style="width: 200px" class="ml-10 mb-10" clearable :placeholder="$t('STATE')">
        <el-option
          v-for="(item, index) in dictList.PROCESS_TASK_STATE"
          :key="index"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-date-picker
        v-model="form.dateTime"
        class="ml-10 mb-10"
        type="datetimerange"
        value-format="yyyy-MM-dd HH:mm:ss"
        :start-placeholder="$t('START_TIME')"
        range-separator="-"
        :end-placeholder="$t('END_TIME')"
        style="width: 320px"
        @change="search"
      />
      <el-input
        v-model.trim="form.processName"
        class="ml-10 mb-10"
        style="width: 200px"
        size="mini"
        clearable
        maxlength="32"
        :placeholder="$t('PROCESS_TASK_NAME') + '/' + $t('SERVICE_NAME')"
        @keyup.enter.native="$debounce(search)"
      />
      <el-button type="primary" class="ml-10 mb-10" @click="$debounce(search)">{{ $t('QUERY') }}</el-button>
    </div>
    <el-table
      ref="tableBox"
      :data="tableData"
      style="width: 100%"
      height="100%"
      :row-class-name="getRowClass"
      class="mainProcessTable"
      border
    >
      <template slot="empty">
        <NullData />
      </template>
      <el-table-column type="index" :label="$t('SEQUENCE')" :width="resetSize(60)" align="center">
        <template slot-scope="scope">
          {{ pageData.size * (pageData.page - 1) + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('PROCESS_TASK_NAME')"
        show-overflow-tooltip
        prop="processName"
        align="left"
      />
      <el-table-column
        :label="$t('SERVICE_NAME')"
        show-overflow-tooltip
        prop="bizName"
        align="left"
      />
      <el-table-column :label="$t('PROCESS_TYPE')" prop="bizType" align="left">
        <template slot-scope="scope">
          <span>{{ setBizType(scope.row.bizType) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('EXECUTION_TIME')" align="left">
        <template slot-scope="scope">
          {{ getStartTime(scope.row) }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('PROGRESS')" prop="process" align="left">
        <template slot-scope="scope">
          <el-progress
            :color="scope.row.status === 'exception' ? '#F56C6C' : '#67C23A'"
            :percentage="scope.row.progressStr || 0"
          />
        </template>
      </el-table-column>
      <el-table-column :label="$t('STATE')" prop="status" align="left">
        <template slot-scope="scope">
          <span>{{ setTaskStatus(scope.row.status) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('CREATOR')" prop="creator" align="left" />
      <el-table-column :label="$t('CREATION_TIME')" prop="createTime" align="left" />
      <el-table-column :label="$t('OPERATE')" class-name="operate-cell" :width="resetSize(60)" align="left">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="viewClick(scope.row)">{{
            $t('VIEW')
          }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="text-right mt-10"
      background
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageData.total"
      :page-size="pageData.size"
      :current-page="pageData.page"
      @size-change="sizeChange"
      @current-change="currentChange"
    />
    <!--查看-->
    <Viewdialog
      :children-task-list="childrenTaskList"
      :visible="taskListDialogVisible"
      :row-data="rowData"
      :region-device-list="regionDeviceList"
      @loadData="loadData"
      @close="viewdialogClose"
    />
  </div>
</template>

<script>
  import { mapGetters } from 'vuex'
  import TaskGroupApi from '@/api/oen/TaskGroup'
  import nodeApi from '@/api/oen/NodeApi'
  import Viewdialog from './components/View.vue'
  let searchData = {} // 查询参数 只有点了查询有效
  export default {
    components: { Viewdialog },
    data() {
      return {
        taskListDialogVisible: false, // 任务列表显示
        childrenTaskList: [], // 任务列表
        processId: '', // 主流程id
        taskDesc: '', // 自定义任务类型
        taskId: '', // 自定义停止任务id
        form: {
          processName: '',
          processId: '',
          bizType: '',
          status: '',
          dateTime: ''
        },
        pageData: {
          page: 1,
          size: 20,
          total: 0
        },
        tableData: [],
        taskIds: [],
        rowData: {},
        regionDeviceList: [],
        messageData: null,
        messageTimer: null,
        errorMessage: null
      }
    },
    computed: {
      ...mapGetters(['dictList', 'taskProcess', 'processList']),
      permission() {
        return this.$store.getters.getAuthData('info:process')
      }
    },
    watch: {
      taskProcess: {
        // 监听任务进度 改变列表数据
        handler(newVal) {
          console.log('监听任务进度 改变列表数据-----', newVal)
          // 如果没有在当前页面就不往下执行了
          if (this.$route.name !== 'MENU_PROCESS_LIST') return
          if (parseInt(newVal.progress) === 100) {
            this.loadData()
            return
          }
          this.tableData.forEach(progressItem => {
            let mainNum = 0
            if (progressItem.children && progressItem.children.length) {
              progressItem.children.forEach(mainTask => {
                let subNum = 0
                mainTask.children.forEach(sub => {
                  const progress = parseInt(newVal.progress) || 0
                  if (sub.subTaskId === newVal.taskId) {
                    if (newVal.error || newVal.errorInfo) {
                      const _this = this
                      this.messageTimer && clearTimeout(this.messageTimer)
                      this.messageTimer = null
                      if (
                        this.messageData &&
                        this.messageData.deviceId &&
                        this.messageData.deviceId === newVal.deviceId
                      ) {
                        this.messageTimer = setTimeout(() => {
                          _this.errorMessage.close()
                        }, 3000)
                        return
                      }
                      this.messageData = newVal
                      this.$message.closeAll()
                      this.errorMessage = this.$message({
                        message: this.$utils.handleServiceI18n(newVal.errorInfo.desc),
                        type: 'error',
                        duration: 0,
                        onClose: () => {
                          _this.messageData = null
                        }
                      })
                      this.messageTimer = setTimeout(() => {
                        _this.errorMessage && _this.errorMessage.close()
                      }, 3000)
                      this.loadData()
                      return
                    }
                    sub.progressStr = progress > sub.progressStr ? progress : sub.progressStr
                    if (progress >= 100 && sub.status !== 'STOP') {
                      sub.status = 'SUCCESS'
                      sub.endTime = newVal.endTime
                    }
                    if (progress > 0 && !sub.startTime && sub.status === 'READY') {
                      sub.status = 'PROCESS'
                      sub.startTime = newVal.startTime
                    }
                  }
                  subNum += sub.progressStr
                })
                mainTask.progressStr = parseInt(subNum / mainTask.children.length)
                mainNum += mainTask.progressStr
                if (mainTask.progressStr >= 100 && mainTask.status !== 'STOP') {
                  mainTask.status = 'SUCCESS'
                  mainTask.endTime = newVal.endTime
                }
                if (mainTask.progressStr > 0 && mainTask.status === 'READY') {
                  mainTask.status = 'PROCESS'
                }
              })
              progressItem.progressStr = parseInt(mainNum / progressItem.children.length)
              if (progressItem.progressStr >= 100 && progressItem.status !== 'STOP') {
                progressItem.status = 'SUCCESS'
              }
              if (progressItem.progressStr > 0 && progressItem.status === 'READY') {
                progressItem.status = 'PROCESS'
              }
            }
          })
        },
        deep: true
      }
    },
    created() {
      this.getRegionDeviceList()
    },
    activated() {
      // 30秒刷新页面
      if (this.$route.params.processId) {
        // 如果有任务清除条件筛选
        this.form = {
          bizType: '',
          status: '',
          dateTime: '',
          processName: ''
        }
        searchData = {}
        const { processId, taskId } = this.$route.params
        this.processId = processId
        this.form.processId = processId
        this.taskIds = taskId
      }
      this.loadData()
    },
    deactivated() {
      this.timingGetList(false)
    },
    beforeDestroy() {
      this.timingGetList(false)
    },
    methods: {
      timingGetList(timing = true) {
        // 30秒刷新页面
        const that = this
        this.intervalTimer && clearTimeout(this.intervalTimer)
        this.intervalTimer = null
        if (!timing) return
        this.intervalTimer = setTimeout(() => {
          that.loadData(true)
        }, 10 * 1000)
      },
      getRegionDeviceList() {
        this.regionDeviceList = []
        nodeApi.regionDeviceList().then(res => {
          this.regionDeviceList = res
        })
      },
      search() {
        this.pageData.page = 1
        searchData = {
          ...this.form
        }
        if (this.form.processName) searchData.processName = this.form.processName
        if (this.form.bizType) searchData.bizType = this.form.bizType
        if (this.form.status) searchData.status = this.form.status
        if (this.form.dateTime) {
          searchData.startTime = this.form.dateTime[0]
          searchData.endTime = this.form.dateTime[1]
        }
        this.loadData()
      },
      loadData(hideLoading = false) {
        const data = {
          page: this.pageData.page,
          size: this.pageData.size,
          hideLoading: hideLoading,
          ...searchData
        }
        if (this.form.processId) data.processId = this.form.processId
        if (!this.taskListDialogVisible) this.rowData = {}
        TaskGroupApi.getTaskGroupList(data)
          .then(res => {
            if (res) {
              const { list, total } = res
              const tableList = this.resetChildren(list)
              // 自定义 prop taskId
              tableList.forEach(item => {
                if (item.children && item.children.length) {
                  item.progressStr = parseInt(item.progress) || 0
                  item.children.forEach(mainItem => {
                    mainItem.taskId = mainItem.mainTaskId
                    mainItem.creator = item.creator
                    mainItem.progressStr = parseInt(mainItem.progress) || 0
                    mainItem.description =
                      (mainItem.description &&
                        this.$utils.handleServiceI18n(mainItem.description)) ||
                      ''
                    if (mainItem.children && mainItem.children.length) {
                      mainItem.children.forEach(sub => {
                        sub.taskId = sub.subTaskId
                        sub.creator = item.creator
                        sub.description =
                          (sub.description && this.$utils.handleServiceI18n(sub.description)) || ''
                        sub.progressStr = parseInt(sub.progress) || 0
                      })
                    }
                  })
                }
                if (
                  this.processId ||
                  (this.taskListDialogVisible && item.processId === this.rowData.processId)
                ) {
                  this.$nextTick(() => {
                    this.processId = ''
                    this.viewClick(item)
                  })
                }
              })
              this.tableData = tableList
              console.log(this.tableData)
              this.pageData.total = total
              this.timingGetList(true)
            }
          })
          .finally(res => {

          })
      },
      resetChildren(list) {
        // 添加children
        list.forEach(item => {
          if (item.taskList && item.taskList.length) {
            item.children = item.taskList
            item.children.forEach(obj => {
              obj.taskId = obj.mainTaskId
              obj.taskDesc = 'main'
            })
            this.resetChildren(item.taskList)
          } else if (item.subTaskList && item.subTaskList.length) {
            item.children = item.subTaskList
            item.children.forEach(obj => {
              obj.taskId = obj.subTaskId
              obj.taskDesc = 'sub'
            })
          }
        })
        return list
      },
      stopTaskGroup(currentRow) {
        // 停止住流程
        TaskGroupApi.stopTaskGroup({
          processId: currentRow.processId,
          processName: currentRow.processName
        })
          .then(res => {
            if (res) {
              this.$message.success(this.$t('EXECUTE_RESULT_SUCCESS'))
              this.loadData()
            }
          })
          .catch(error => {
            console.log(error)
          })
      },
      viewClick(row) {
        // 查看任务列表
        this.childrenTaskList = row.children
        console.log(this.childrenTaskList)
        this.rowData = row
        this.taskListDialogVisible = true
      },
      setBizType(bizType) {
        const data = this.dictList.BUSINESS_TYPES.find(item => item.value === bizType)
        return data ? data.label : ''
      },
      setTaskStatus(status) {
        const data = this.dictList.PROCESS_TASK_STATE.find(item => item.value === status)
        return data ? data.label : ''
      },
      showStopTaskGroup(currentRow) {
        // 停止主流程任务提示
        // 显示主流程弹窗
        this.processId = currentRow.processId
        this.$confirm(
          this.$t('ARE_YOU_SURE_STOP_ALLTASKS_NDER_PROCESS'),
          this.$t('STOP_THE_MAIN_PROCESS'),
          {
            confirmButtonText: this.$t('YES'),
            cancelButtonText: this.$t('CANCEL'),
            type: 'warning'
          }
        )
          .then(() => {
            this.stopTaskGroup(currentRow)
          })
          .catch(err => {
            console.log(err)
          })
      },
      // 取消任务
      cancelTask(currentRow) {
        this.$confirm(this.$t('CANCEL_PROCESS'))
          .then(() => {
            TaskGroupApi.cancelTaskGroup({
              processId: currentRow.processId,
              processName: currentRow.processName
            })
              .then(res => {
                if (res) {
                  this.$message.success(this.$t('OPERATE_SUCCESS'))
                  this.loadData()
                }
              })
              .catch(error => {
                console.log(error)
              })
          })
          .catch(err => {
            console.log(err)
          })
      },
      viewdialogClose() {
        this.taskListDialogVisible = false
        this.processId = ''
        this.form.processId = ''
        this.$route.params && this.$route.params.needBack && this.$router.push({
          name: this.$route.params.backUrl
        })
      },
      sizeChange(size) {
        this.pageData.size = size
        this.loadData()
      },
      currentChange(page) {
        this.pageData.page = page
        this.loadData()
      },
      getRowClass(row) {
        // 添加class
        const data = row.row
        const res = []
        if (data.children && data.children.length > 0) {
          res.push('row-expand-has')
          return res
        } else {
          res.push('row-expand-unhas')
          return res
        }
      },
      getStartTime(rowData) {
        const timeList = rowData.taskList.map(i => {
          return {
            second: new Date(i.startTime || '').getTime(),
            time: i.startTime
          }
        })
        timeList.sort((a, b) => a.second - b.second)
        return timeList[0].time
      }
    }
  }
</script>

<style lang="scss">
  .row-expand-unhas .el-table__expand-column .el-table__expand-icon {
    display: none;
  }
  .mainProcessTable,
  .processDialog {
    .el-progress {
      display: flex;
      align-items: center;
    }
    .el-progress__text {
      word-break: normal;
      width: 50px;
    }
  }
</style>
